<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of mmw_mapper_WebpageMapper
 *
 * @author Manu
 */
require_once("mmw_mapper_Mapper.php");
require_once(dirname(__FILE__) . '/../domain/mmw_domain_Webpage.php');

class mmw_mapper_WebpageMapper extends mmw_mapper_Mapper {
    private $insertStmt;
    private $deleteStmt;
    private $findByUrlStmt;
    
    public function __construct() {
        parent::__construct();
        
        $this->insertStmt=self::$PDO->prepare(
                "INSERT INTO webpage (url, title) VALUES (?,?)");
        
        $this->deleteStmt=self::$PDO->prepare(
                "DELETE FROM webpage WHERE id=?");
        
        $this->findByUrlStmt=self::$PDO->prepare(
                "SELECT * FROM webpage  WHERE url=?");
    }
    
    public function insert(mmw_domain_DomainObject $object) {
        $values=array($object->getUrl(), $object->getTitle());
        $this->insertStmt->execute($values);
        $id=self::$PDO->lastInsertId();
        $object->setId($id);
    }
    
    public function delete($id) {
        $values=array($id);
        $this->deleteStmt->execute($values);
    }
    
    public function findByUrl($url) {
        $values=array($url);
        $this->findByUrlStmt->execute($values);
        $arResults=$this->findByUrlStmt->fetch();
        $this->findByUrlStmt->closeCursor();
        
        if (!is_array($arResults)) { return null; }
        else if (!isset($arResults['id'])) { return null; }
        
        $webpage=$this->createObject($arResults);
        return $webpage;
    }
    
    protected function createObject($array) {
        $webpage=new mmw_domain_Webpage();
        $webpage->setId($array['id']);
        $webpage->setUrl($array['url']);
        $webpage->setTitle($array['title']);
        
        return $webpage;
    }
}

?>
